package com.wk.myhandle;

public class MyLooper {

    final MyMessageQueue mQueue;
    private static ThreadLocal<MyLooper> sThreadLocal = new ThreadLocal<>();

    private MyLooper() {
        mQueue = new MyMessageQueue();
    }


    public static void prepare() {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new MyLooper());
    }

    public static MyLooper myLooper() {
        return sThreadLocal.get();
    }

    public static void loop(){
        final MyLooper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MyMessageQueue queue = me.mQueue;
        for(;;){
            MyMessage msg = queue.next();
            if(msg == null){
                continue;
            }
            msg.target.dispatchMessage(msg);
        }
    }
}